// pages/volunteer/apply.js
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    name: '',
    genderIndex: -1,
    genderOptions: [
      { value: 'male', label: '男' },
      { value: 'female', label: '女' }
    ],
    phone: '',
    student_id: '',
    department: '',
    grade: '',
    experience: '',
    available_time: '',
    self_introduction: '',

    canSubmit: false,
    submitting: false
  },

  onLoad() {
    // 预填姓名/手机号
    const user = app?.globalData?.userInfo || {}
    this.setData({
      name: user.real_name || user.nickname || '',
      phone: user.phone || ''
    })
    this.updateCanSubmit()
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({ [field]: e.detail.value })
    this.updateCanSubmit()
  },

  onGenderChange(e) {
    const i = Number(e.detail.value)
    this.setData({ genderIndex: i })
    this.updateCanSubmit()
  },

  isValidPhone(phone) { return /^1[3-9]\d{9}$/.test(String(phone||'').trim()) },

  updateCanSubmit() {
    const { name, genderIndex, phone } = this.data
    const nameOk = !!name && String(name).trim().length <= 50
    const genderOk = genderIndex >= 0
    const phoneOk = this.isValidPhone(phone)
    this.setData({ canSubmit: nameOk && genderOk && phoneOk })
  },

  async submit() {
    if (!this.data.canSubmit || this.data.submitting) return

    const ok = await app.checkAuth()
    if (!ok) return

    this.setData({ submitting: true })
    try {
      const payload = {
        name: this.data.name.trim(),
        gender: this.data.genderOptions[this.data.genderIndex].value,
        phone: this.data.phone.trim(),
        student_id: this.data.student_id || undefined,
        department: this.data.department || undefined,
        grade: this.data.grade || undefined,
        experience: this.data.experience || undefined,
        available_time: this.data.available_time || undefined,
        self_introduction: this.data.self_introduction || undefined
      }

      const res = await api.volunteer.apply(payload)
      wx.showToast({ title: '提交成功', icon: 'success' })
      // 跳转到"我的申请"页，或返回
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/volunteer/my-application' })
      }, 600)
    } catch (err) {
      wx.showToast({ title: err.message || '提交失败', icon: 'none' })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 入口：我的报名
  async goMyApplication() {
    const ok = await app.checkAuth?.()
    if (!ok) return
    wx.navigateTo({ url: '/pages/volunteer/my-application' })
  }
})